// content.js
(function () {
    'use strict';

    class StablePrintBlocker {
        constructor() {
            this.blocked = false;
            this.printUrls = new Set(); // 存储发现的打印URL
            this.init();
        }

        init() {
            console.log('🛡️ 打印拦截器初始化');
            this.watchForPrintElements();
            this.cleanExistingElements();
        }

        watchForPrintElements() {
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    mutation.addedNodes.forEach((node) => {
                        this.handleNewNode(node);
                    });
                });
            });

            observer.observe(document.body, {
                childList: true, subtree: true
            });

            this.observer = observer;
        }

        handleNewNode(node) {
            // 处理 printIframeContainer - 先获取src再删除
            if (node.id === 'printIframeContainer') {
                console.log('🛡️ 发现 printIframeContainer，开始分析内容...');
                this.analyzePrintContainer(node);
                return;
            }

            // 处理 iframe - 先获取src再删除
            if (node.nodeName === 'IFRAME') {
                console.log('🛡️ 发现 iframe，开始分析...');
                this.analyzeIframe(node);
                return;
            }

            // 处理子节点中的相关元素
            if (node.querySelectorAll) {
                const containers = node.querySelectorAll('#printIframeContainer');
                containers.forEach(container => this.analyzePrintContainer(container));

                const iframes = node.querySelectorAll('iframe');
                iframes.forEach(iframe => this.analyzeIframe(iframe));
            }
        }

        analyzePrintContainer(container) {
            console.group('📋 printIframeContainer 分析报告');

            // 记录容器基本信息
            console.log('🏷️ 容器信息:', {
                id: container.id,
                className: container.className,
                style: container.style.cssText,
                innerHTML: container.innerHTML ? container.innerHTML.substring(0, 500) + '...' : '空'
            });

            // 查找所有 iframe
            const iframes = container.querySelectorAll('iframe');
            console.log(`📊 容器内 iframe 数量: ${iframes.length}`);

            iframes.forEach((iframe, index) => {
                console.log(`📄 iframe ${index + 1}:`, this.getIframeInfo(iframe));
            });

            // 查找其他可能包含URL的元素
            this.findUrlsInContainer(container);

            console.groupEnd();

            // 延迟一小段时间再删除，确保信息被记录
            setTimeout(() => {
                container.remove();
                console.log('✅ printIframeContainer 已移除');
            }, 100);
        }

        analyzeIframe(iframe) {
            const iframeInfo = this.getIframeInfo(iframe);

            console.group('📋 iframe 分析报告');
            console.log('🏷️ iframe 详细信息:', iframeInfo);

            // 如果iframe有src，记录下来
            if (iframeInfo.src) {
                this.recordPrintUrl(iframeInfo.src, 'iframe-src');
            }

            // 检查iframe的内容（如果同源）
            this.tryAnalyzeIframeContent(iframe);

            console.groupEnd();

            // 延迟删除
            setTimeout(() => {
                iframe.remove();
                console.log('✅ iframe 已移除');
            }, 100);
        }

        getIframeInfo(iframe) {
            const info = {
                src: iframe.src,
                name: iframe.name,
                id: iframe.id,
                className: iframe.className,
                style: iframe.style.cssText,
                width: iframe.width,
                height: iframe.height,
                sandbox: iframe.sandbox,
                allow: iframe.allow
            };

            // 尝试获取更多属性
            try {
                const attributes = iframe.getAttributeNames();
                info.attributes = {};
                attributes.forEach(attr => {
                    if (!['src', 'name', 'id', 'class', 'style', 'width', 'height', 'sandbox', 'allow'].includes(attr)) {
                        info.attributes[attr] = iframe.getAttribute(attr);
                    }
                });
            } catch (e) {
                info.attributesError = e.message;
            }

            return info;
        }

        findUrlsInContainer(container) {
            const urlElements = [];

            // 查找所有可能包含URL的元素
            const elementsWithSrc = container.querySelectorAll('[src]');
            const elementsWithHref = container.querySelectorAll('[href]');
            const elementsWithData = container.querySelectorAll('[data-src], [data-url]');
            const scripts = container.querySelectorAll('script');

            elementsWithSrc.forEach(el => {
                const src = el.getAttribute('src');
                if (src) {
                    urlElements.push({type: 'src', element: el.tagName, url: src});
                    this.recordPrintUrl(src, `${el.tagName}-src`);
                }
            });

            elementsWithHref.forEach(el => {
                const href = el.getAttribute('href');
                if (href) {
                    urlElements.push({type: 'href', element: el.tagName, url: href});
                    this.recordPrintUrl(href, `${el.tagName}-href`);
                }
            });

            elementsWithData.forEach(el => {
                const dataSrc = el.getAttribute('data-src');
                const dataUrl = el.getAttribute('data-url');

                if (dataSrc) {
                    urlElements.push({type: 'data-src', element: el.tagName, url: dataSrc});
                    this.recordPrintUrl(dataSrc, `${el.tagName}-data-src`);
                }
                if (dataUrl) {
                    urlElements.push({type: 'data-url', element: el.tagName, url: dataUrl});
                    this.recordPrintUrl(dataUrl, `${el.tagName}-data-url`);
                }
            });

            // 分析script内容中的URL
            scripts.forEach((script, index) => {
                const content = script.textContent || script.innerHTML;
                if (content) {
                    this.extractUrlsFromScript(content, `script-${index}`);
                }
            });

            if (urlElements.length > 0) {
                console.log('🔗 发现的URL链接:', urlElements);
            }
        }

        extractUrlsFromScript(scriptContent, source) {
            // 简单的URL正则匹配
            const urlRegex = /(https?:\/\/[^\s"'<>]+|blob:[^\s"'<>]+|data:[^\s"'<>]+)/gi;
            const matches = scriptContent.match(urlRegex);

            if (matches) {
                console.log(`📜 ${source} 中的URL:`, matches);
                matches.forEach(url => this.recordPrintUrl(url, `script-${source}`));
            }

            // 查找打印相关的变量赋值
            const printVarRegex = /(printSrc|printUrl|iframeSrc|src\s*=\s*['"][^'"]+['"])/gi;
            const printMatches = scriptContent.match(printVarRegex);

            if (printMatches) {
                console.log(`📜 ${source} 中的打印相关变量:`, printMatches);
            }
        }

        tryAnalyzeIframeContent(iframe) {
            // 尝试访问iframe的内容（仅限同源）
            setTimeout(() => {
                try {
                    if (iframe.contentDocument && iframe.contentDocument.URL) {
                        console.log('🔍 iframe 内部URL:', iframe.contentDocument.URL);
                        this.recordPrintUrl(iframe.contentDocument.URL, 'iframe-content');

                        // 检查iframe内部的打印相关元素
                        const iframePrintElements = iframe.contentDocument.querySelectorAll('[onclick*="print"], button, [class*="print"]');
                        if (iframePrintElements.length > 0) {
                            console.log('🔍 iframe 内部打印元素:', iframePrintElements.length);
                        }
                    }
                } catch (e) {
                    // 跨域限制，无法访问
                    console.log('🔒 iframe 内容访问受限（跨域）');
                }
            }, 200);
        }

        recordPrintUrl(url, source) {
            if (!this.printUrls.has(url)) {
                this.printUrls.add(url);
                console.log('🎯 新发现的打印URL:', {
                    url: url, source: source, timestamp: new Date().toISOString()
                });

                // 这里可以添加更多分析逻辑
                this.analyzePrintUrl(url, source);
            }
        }

        analyzePrintUrl(url, source) {
            console.group('🔍 URL分析');
            console.log('📊 URL:', url);
            console.log('📁 来源:', source);

            // 分析URL类型
            if (url.startsWith('blob:')) {
                console.log('📄 类型: Blob URL (可能包含打印数据)');
            } else if (url.startsWith('data:')) {
                console.log('📄 类型: Data URL (内联数据)');
                console.log('📋 Data URL 内容预览:', url.substring(0, 200) + '...');
            } else if (url.includes('print')) {
                console.log('🎯 包含 "print" 关键字');
            } else if (url.includes('waybill')) {
                console.log('📦 可能是运单相关');
            }

            // 可以在这里添加更多自定义分析逻辑
            console.groupEnd();
        }

        cleanExistingElements() {
            // 清理现有的打印元素
            setTimeout(() => {
                const container = document.getElementById('printIframeContainer');
                if (container) {
                    console.log('🛡️ 清理现有 printIframeContainer');
                    this.analyzePrintContainer(container);
                }

                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(iframe => {
                    console.log('🛡️ 清理现有 iframe');
                    this.analyzeIframe(iframe);
                });

                console.log('✅ 现有打印元素已清理');
            }, 100);
        }

        // 获取所有发现的打印URL
        getDiscoveredUrls() {
            return Array.from(this.printUrls);
        }

        setDiscoveredUrls() {
            this.printUrls = new Set();
        }

        // 生成分析报告
        generateReport() {
            console.group('📊 打印拦截分析报告');
            console.log('🕒 报告时间:', new Date().toISOString());
            console.log('🔗 发现的URL数量:', this.printUrls.size);
            console.log('📋 所有URL:', this.getDiscoveredUrls());
            console.log('🛡️ 拦截状态:', this.blocked ? '活跃' : '未激活');
            console.groupEnd();

            return {
                timestamp: new Date().toISOString(),
                urlCount: this.printUrls.size,
                urls: this.getDiscoveredUrls(),
                blocked: this.blocked
            };
        }

        destroy() {
            if (this.observer) {
                this.observer.disconnect();
            }

            // 生成最终报告
            this.generateReport();

            console.log('🛡️ 打印拦截器已销毁');
        }
    }

    class LogisticsExporter {
        constructor() {
            this.isProcessing = false;
            this.currentIndex = 0;
            this.results = [];
            this.settings = {
                autoUncheckPacking: true, processDelay: 3000, pdfNaming: 'waybill'
            };

            console.log('🔄 LogisticsExporter构造函数调用');
            this.init();
        }

        init() {
            console.log('🚚 物流面单导出工具已加载');

            // 修复消息监听 - 确保只绑定一次
            if (!this.messageListenerBound) {
                chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
                    console.log('📩 Content收到消息:', request.action);
                    return this.handleMessage(request, sender, sendResponse);
                });
                this.messageListenerBound = true;
                console.log('✅ 消息监听器已绑定');
            }

            // 注入样式
            this.injectStyles();

            // 预加载必要库
            this.preloadLibraries();
        }

        async handleMessage(request, sender, sendResponse) {
            console.log('🔄 处理消息:', request.action);

            try {
                switch (request.action) {
                    case 'getStatus':
                        console.log('📊 获取页面状态');
                        const status = this.getPageStatus();
                        sendResponse({
                            success: true, data: status
                        });
                        break;

                    case 'startExport':
                        console.log('🚀 开始导出处理');
                        // 异步处理，立即响应
                        sendResponse({success: true});
                        // 异步执行导出
                        this.startExport(request.settings).catch(error => {
                            console.error('导出过程错误:', error);
                            this.sendExportError(error.message);
                        });
                        break;

                    case 'stopExport':
                        console.log('⏹️ 停止导出');
                        this.stopExport();
                        sendResponse({success: true});
                        break;

                    case 'ping':
                        console.log('🏓 收到ping请求');
                        sendResponse({success: true, message: 'pong'});
                        break;

                    // 新增：删除全部打印对话框
                    case 'removeAllDialogs':
                        const removedCount = this.removeAllPrintDialogs();
                        sendResponse({
                            success: true,
                            removedCount: removedCount,
                            message: `成功删除 ${removedCount} 个对话框`
                        });
                        break;

                    // 新增：关闭所有模态框
                    case 'closeAllModals':
                        this.closeAllModals();
                        sendResponse({
                            success: true,
                            message: '所有模态框已关闭'
                        });
                        break;

                    // 新增：清理页面状态
                    case 'cleanupPage':
                        this.removeAllPrintDialogs();
                        this.closeAllModals();
                        sendResponse({
                            success: true,
                            message: '页面清理完成'
                        });
                        break;
                    default:
                        console.warn('❓ 未知操作:', request.action);
                        sendResponse({success: false, error: '未知操作'});
                }
            } catch (error) {
                console.error('❌ 处理消息错误:', error);
                sendResponse({
                    success: false, error: error.message
                });
            }

            return true; // 保持消息通道开放
        }

        // 修复getPageStatus方法，确保返回正确的数据结构
        getPageStatus() {
            try {
                const waybills = this.getAllWaybills();
                const printableCount = waybills.filter(w => w.打印按钮).length;
                const isSupported = this.isSupportedPage();

                console.log('📊 页面状态检查结果:', {
                    totalWaybills: waybills.length, printableCount: printableCount, isSupported: isSupported
                });

                return {
                    totalWaybills: waybills.length, printableCount: printableCount, // 修复字段名，与popup匹配
                    isSupportedPage: isSupported, pageTitle: document.title, url: window.location.href
                };
            } catch (error) {
                console.error('❌ 获取页面状态错误:', error);
                return {
                    totalWaybills: 0,
                    printableCount: 0,
                    isSupportedPage: false,
                    pageTitle: document.title,
                    url: window.location.href,
                    error: error.message
                };
            }
        }

        // 修复sendProgressUpdate方法，添加错误处理
        sendProgressUpdate(current, total, message, currentWaybill = '', type = 'info') {
            try {
                chrome.runtime.sendMessage({
                    action: 'progressUpdate', data: {
                        current: current, total: total, message: message, currentWaybill: currentWaybill, type: type
                    }
                }).then(() => {
                    console.log('📤 进度更新发送成功:', message);
                }).catch(error => {
                    console.warn('⚠️ 进度更新发送失败:', error.message);
                });
            } catch (error) {
                console.warn('⚠️ 发送进度更新异常:', error.message);
            }
        }

        // 修复其他发送消息的方法
        sendExportComplete(fileName, successCount) {
            try {
                chrome.runtime.sendMessage({
                    action: 'exportComplete', data: {
                        fileName: fileName,
                        total: this.results.length,
                        success: successCount,
                        failed: this.results.length - successCount,
                        zipGenerated: true
                    }
                }).then(() => {
                    console.log('✅ 导出完成消息发送成功');
                }).catch(error => {
                    console.warn('⚠️ 导出完成消息发送失败:', error.message);
                });
            } catch (error) {
                console.warn('⚠️ 发送导出完成消息异常:', error.message);
            }
        }

        sendExportError(error) {
            try {
                chrome.runtime.sendMessage({
                    action: 'exportError', data: {error: error}
                }).then(() => {
                    console.log('❌ 导出错误消息发送成功');
                }).catch(sendError => {
                    console.warn('⚠️ 导出错误消息发送失败:', sendError.message);
                });
            } catch (error) {
                console.warn('⚠️ 发送导出错误消息异常:', error.message);
            }
        }

        isSupportedPage() {
            // 检查是否在运单列表页面 - 根据您提供的HTML结构
            // const hasTable = document.querySelector('[data-testid="beast-core-table-body-tr"]') !== null;
            // const hasWaybillNumbers = document.querySelector('.PiGlI4-A') !== null;
            // const hasPrintButtons = document.querySelector('a[data-testid="beast-core-button-link"]') !== null;
            //
            // return hasTable && hasWaybillNumbers && hasPrintButtons;
            console.log('🔍 开始检测页面支持性...');

            // 检查URL是否匹配
            const url = window.location.href;
            const isTemuPage = url.includes('temu.com');

            console.log('📄 页面URL:', url);
            console.log('🏷️ 是否Temu页面:', isTemuPage);

            // 检查关键元素 - 使用更宽松的条件
            const hasTable = document.querySelector('[data-testid="beast-core-table-body-tr"]') !== null ||
                document.querySelector('.TB_tr_123') !== null;

            const hasWaybillNumbers = document.querySelector('.PiGlI4-A') !== null ||
                document.querySelector('div[class*="tracking"]') !== null;

            console.log('📊 页面元素检测结果:', {
                hasTable: hasTable,
                hasWaybillNumbers: hasWaybillNumbers
            });

            // 更宽松的支持条件：只要在Temu相关页面且有表格结构就支持
            const isSupported = isTemuPage && hasTable;

            console.log('✅ 页面支持性结果:', isSupported);

            return isSupported;
        }

        // 修改 getAllWaybills 方法，增加获取CW单号和服务商品牌
        // getAllWaybills() {
        //     const waybills = [];
        //
        //     try {
        //         // 方法1: 通过数据属性查找
        //         const rows = document.querySelectorAll('[data-testid="beast-core-table-body-tr"]');
        //         console.log('找到表格行:', rows.length);
        //
        //         rows.forEach((row, index) => {
        //             try {
        //                 // 提取物流单号 - 根据您提供的HTML结构
        //                 const trackingDiv = row.querySelector('.PiGlI4-A');
        //                 const trackingNumber = trackingDiv ? trackingDiv.textContent.trim() : '';
        //
        //                 // 提取订单号
        //                 const orderLinks = row.querySelectorAll('a[data-testid="beast-core-button-link"]');
        //                 let orderNumber = '';
        //                 for (let link of orderLinks) {
        //                     const text = link.textContent.trim();
        //                     if (text && text.startsWith('PO-')) {
        //                         orderNumber = text;
        //                         break;
        //                     }
        //                 }
        //
        //                 // 查找打印按钮
        //                 const printButton = Array.from(row.querySelectorAll('a[data-testid="beast-core-button-link"]'))
        //                     .find(btn => btn.textContent == '打印物流面单');
        //
        //                 // 新增：获取CW单号
        //                 const cwNumber = this.extractCWNumber(row);
        //
        //                 // 新增：获取服务商品牌
        //                 const serviceBrand = this.extractServiceBrand(row);
        //
        //                 if (trackingNumber) {
        //                     waybills.push({
        //                         序号: index + 1, 客户单号: orderNumber, 物流单号: trackingNumber, CW单号: cwNumber, // 新增字段
        //                         服务商品牌: serviceBrand, // 新增字段
        //                         打印按钮: printButton, rowElement: row, success: false, error: null
        //                     });
        //                 }
        //             } catch (rowError) {
        //                 console.error('处理行数据错误:', rowError);
        //             }
        //         });
        //
        //         // 方法2: 如果方法1没找到，尝试其他选择器
        //         if (waybills.length === 0) {
        //             console.log('尝试备用选择器...');
        //             const backupRows = document.querySelectorAll('.TB_tr_123');
        //             backupRows.forEach((row, index) => {
        //                 const trackingElements = row.querySelectorAll('div');
        //                 for (let element of trackingElements) {
        //                     const text = element.textContent.trim();
        //                     if (text && text.match(/^[A-Z0-9]{16,20}$/)) {
        //                         const cwNumber = this.extractCWNumber(row);
        //                         const serviceBrand = this.extractServiceBrand(row);
        //
        //                         waybills.push({
        //                             序号: index + 1,
        //                             物流单号: text,
        //                             CW单号: cwNumber,
        //                             服务商品牌: serviceBrand,
        //                             打印按钮: null,
        //                             rowElement: row,
        //                             success: false,
        //                             error: null
        //                         });
        //                         break;
        //                     }
        //                 }
        //             });
        //         }
        //
        //     } catch (error) {
        //         console.error('获取运单列表错误:', error);
        //     }
        //
        //     console.log('最终运单列表:', waybills);
        //     return waybills;
        // }



        extractTrackingNumber(row) {
            try {
                const table = row.closest('[data-testid="beast-core-table"]');
                if (!table) return '';

                const logisticsServiceIndex = this.getColumnIndex(table, '运单号');
                if (logisticsServiceIndex === -1) return '';

                const cells = row.querySelectorAll('[data-testid="beast-core-table-td"]');
                if (cells.length > logisticsServiceIndex) {
                    const serviceCell = cells[logisticsServiceIndex];
                    const serviceText = serviceCell.textContent.trim();
                    console.log('运单号文本:', serviceText);
                    return  serviceText;
                }
                return '';
            } catch (error) {
                console.warn('提取运单号失败:', error);
                return '';
            }
        }

        // 重新编写：清理运单号文本 - 只提取中文前面的英文数字，去掉特殊符号
        cleanTrackingNumber(text) {
            if (!text) return '';

            console.log('🔧 开始清理文本:', text);

            // 第一步：去掉所有特殊符号（保留字母和数字）
            let cleanText = text.replace(/[^A-Za-z0-9\u4e00-\u9fa5]/g, '');
            console.log('🗑️ 去掉特殊符号后:', cleanText);

            // 第二步：直接查找中文前面的英文数字部分
            // 匹配规则：英文数字组合，直到遇到中文或字符串结束
            const match = cleanText.match(/^[A-Z0-9]+(?=[\u4e00-\u9fa5]|$)/);
            if (match) {
                const trackingNumber = match[0];
                console.log('✅ 提取到中文前的运单号:', trackingNumber);
                return trackingNumber;
            }

            // 第三步：如果没找到中文分隔，提取所有连续英文数字
            const englishNumberMatch = cleanText.match(/[A-Z0-9]{10,20}/);
            if (englishNumberMatch) {
                console.log('✅ 提取到英文数字组合:', englishNumberMatch[0]);
                return englishNumberMatch[0];
            }

            console.log('⚠️ 未找到标准运单号，返回清理后文本:', cleanText);
            return cleanText;
        }


        getAllWaybills() {
            const waybills = [];

            try {
                // 方法1: 通过数据属性查找
                const rows = document.querySelectorAll('[data-testid="beast-core-table-body-tr"]');
                console.log('找到表格行:', rows.length);

                rows.forEach((row, index) => {
                    try {
                        // 提取物流单号 - 根据您提供的HTML结构

                        const trackingNumber = this.cleanTrackingNumber(this.extractTrackingNumber(row));

                        // 提取订单号
                        const orderLinks = row.querySelectorAll('a[data-testid="beast-core-button-link"]');
                        let orderNumber = '';
                        for (let link of orderLinks) {
                            const text = link.textContent.trim();
                            if (text && text.startsWith('PO-')) {
                                orderNumber = text;
                                break;
                            }
                        }

                        // 查找打印按钮
                        const printButton = Array.from(row.querySelectorAll('a[data-testid="beast-core-button-link"]'))
                            .find(btn => btn.textContent == '打印物流面单' );

                        // 新增：获取CW单号
                        const cwNumber = this.extractCWNumber(row);

                        // 新增：获取服务商品牌
                        const serviceBrand = this.extractServiceBrand(row);

                        if (trackingNumber) {
                            waybills.push({
                                序号: index + 1, 客户单号: orderNumber, 物流单号: trackingNumber, CW单号: cwNumber, // 新增字段
                                服务商品牌: serviceBrand, // 新增字段
                                打印按钮: printButton, rowElement: row, success: false, error: null
                            });
                        }
                    } catch (rowError) {
                        console.error('处理行数据错误:', rowError);
                    }
                });

                // 方法2: 如果方法1没找到，尝试其他选择器
                if (waybills.length === 0) {
                    console.log('尝试备用选择器...');
                    const backupRows = document.querySelectorAll('.TB_tr_123');
                    backupRows.forEach((row, index) => {
                        const trackingElements = row.querySelectorAll('div');
                        for (let element of trackingElements) {
                            const text = element.textContent.trim();
                            if (text && text.match(/^[A-Z0-9]{16,20}$/)) {
                                const cwNumber = this.extractCWNumber(row);
                                const serviceBrand = this.extractServiceBrand(row);

                                waybills.push({
                                    序号: index + 1,
                                    物流单号: text,
                                    CW单号: cwNumber,
                                    服务商品牌: serviceBrand,
                                    打印按钮: null,
                                    rowElement: row,
                                    success: false,
                                    error: null
                                });
                                break;
                            }
                        }
                    });
                }

            } catch (error) {
                console.error('获取运单列表错误:', error);
            }

            console.log('最终运单列表:', waybills);
            return waybills;
        }


        // 新增：提取CW单号
        extractCWNumber(row) {
            try {
                // 根据HTML结构，CW单号可能在物流单号附近的其他元素中
                const cwElements = row.querySelectorAll('div, span');
                for (let element of cwElements) {
                    const text = element.textContent.trim();
                    // CW单号通常以CW开头，后面跟数字
                    if (text && (text.match(/^CW\d+/i) || text.match(/^CWE\d+/i))) {
                        return text;
                    }
                }

                // 如果没有找到CW单号，返回空字符串
                return '';
            } catch (error) {
                console.warn('提取CW单号失败:', error);
                return '';
            }
        }


// 通用的列索引获取方法
        getColumnIndex(table, columnName) {
            try {
                const headerRow = table.querySelector('[data-testid="beast-core-table-header-tr"]');
                if (!headerRow) return -1;

                const headerCells = headerRow.querySelectorAll('[data-testid="beast-core-table-th"]');
                for (let i = 0; i < headerCells.length; i++) {
                    const headerText = headerCells[i].textContent.trim();
                    if (headerText === columnName) {
                        return i;
                    }
                }
                return -1;
            } catch (error) {
                console.warn(`获取列索引失败 (${columnName}):`, error);
                return -1;
            }
        }

// 修改后的提取方法
        // 新增：提取服务商品牌
        extractServiceBrand(row) {
            try {
                const table = row.closest('[data-testid="beast-core-table"]');
                if (!table) return '';

                const logisticsServiceIndex = this.getColumnIndex(table, '物流服务');
                if (logisticsServiceIndex === -1) return '';

                const cells = row.querySelectorAll('[data-testid="beast-core-table-td"]');
                if (cells.length > logisticsServiceIndex) {
                    const serviceCell = cells[logisticsServiceIndex];
                    const serviceText = serviceCell.textContent.trim();
                    console.log('物流服务文本:', serviceText);

                    // 根据关键词识别服务商品牌
                    if (serviceText.includes('GOFO EXPRESS')) {
                        return 'GOFO EXPRESS';
                    } else if (serviceText.includes('GOFO')) {
                        return 'GOFO EXPRESS';
                    } else if (serviceText.includes('USPS')) {
                        return 'USPS';
                    } else if (serviceText.includes('UPS')) {
                        return 'UPS';
                    } else if (serviceText.includes('FedEx')) {
                        return 'FedEx';
                    } else if (serviceText.includes('UniUni')) {
                        return 'UniUni';
                    } else {
                        return '';
                    }
                }
                return '';
            } catch (error) {
                console.warn('提取服务商品牌失败:', error);
                return '';
            }
        }

        injectStyles() {
            const style = document.createElement('style');
            style.textContent = `
                .logistics-export-highlight {
                    border: 2px solid #1890ff !important;
                    background: #f0f8ff !important;
                    transition: all 0.3s ease;
                }
                .logistics-export-processing {
                    animation: pulse 1.5s infinite;
                }
                @keyframes pulse {
                    0% { background: #f0f8ff; }
                    50% { background: #e6f7ff; }
                    100% { background: #f0f8ff; }
                }
            `;
            document.head.appendChild(style);
        }

        async startExport(settings) {
            if (this.isProcessing) {
                throw new Error('已有处理任务在进行中');
            }

            this.isProcessing = true;
            this.settings = {...this.settings, ...settings};
            this.results = [];
            this.currentIndex = 0;

            const waybills = this.getAllWaybills();
            // 使用
            window.printBlocker = new StablePrintBlocker();

            console.log('🎯 打印拦截器已启动，输入 printBlocker.generateReport() 查看分析报告');

            if (waybills.length === 0) {
                throw new Error('未找到可处理的运单');
            }

            this.sendProgressUpdate(0, waybills.length, `开始批量处理 ${waybills.length} 个运单`);

            // 开始处理每个运单
            for (let i = 0; i < waybills.length; i++) {
                if (!this.isProcessing) {
                    this.sendProgressUpdate(i, waybills.length, '处理已停止', '', 'info');
                    break;
                }

                const waybill = waybills[i];
                this.currentIndex = i;

                // 高亮当前处理的行
                this.highlightCurrentRow(waybill.rowElement);

                this.sendProgressUpdate(i, waybills.length, `处理中: ${waybill.物流单号}`, waybill.物流单号);

                try {
                    const result = await this.processSingleWaybill(waybill);
                    this.results.push(result);

                    if (result.success) {
                        this.sendProgressUpdate(i + 1, waybills.length, `✅ ${waybill.物流单号} 处理成功`, waybill.物流单号, 'success');
                    } else {
                        this.sendProgressUpdate(i + 1, waybills.length, `❌ ${waybill.物流单号} 处理失败: ${result.error}`, waybill.物流单号, 'error');
                    }
                } catch (error) {
                    const errorResult = {
                        ...waybill, success: false, error: error.message, pdfData: null
                    };
                    this.results.push(errorResult);
                    this.sendProgressUpdate(i + 1, waybills.length, `❌ ${waybill.物流单号} 处理异常: ${error.message}`, waybill.物流单号, 'error');
                }

                // 移除高亮
                this.removeHighlight(waybill.rowElement);

                // 延迟避免操作过快
                if (i < waybills.length - 1 && this.isProcessing) {
                    await this.delay(this.settings.processDelay);
                }
                this.removeAllPrintDialogs();
                this.closeAllModals();
            }

            window.printBlocker.destroy();
            this.removeAllPrintDialogs();
            this.closeAllModals();

            if (this.isProcessing) {
                // 生成Excel文件和PDF ZIP包
                await this.generateExcelFile();
                await this.generatePDFZipPackage();
                this.isProcessing = false;
            }
        }

        highlightCurrentRow(rowElement) {
            if (rowElement) {
                rowElement.classList.add('logistics-export-highlight', 'logistics-export-processing');
            }
        }

        removeHighlight(rowElement) {
            if (rowElement) {
                rowElement.classList.remove('logistics-export-highlight', 'logistics-export-processing');
            }
        }

        async processSingleWaybill(waybill) {
            console.log(`🚀 开始处理运单: ${waybill.物流单号}`);

            try {
                // 1. 点击打印按钮
                await this.clickPrintButton(waybill);

                // 2. 等待打印对话框
                await this.waitForPrintDialog();

                // 3. 取消选择装箱单（如果启用）
                if (this.settings.autoUncheckPacking) {
                    await this.uncheckPackingList();
                }

                // 4. 点击打印确认
                await this.clickPrintConfirmButton();

                // 5. 获取PDF文件
                const pdfResult = await this.getPDFFromPrintPage(waybill);

                // 6. 关闭对话框或返回
                await this.closePrintDialog();

                return {
                    ...waybill,
                    success: pdfResult.success,
                    pdfData: pdfResult.pdfData,
                    pdfBlob: pdfResult.pdfBlob,
                    fileName: pdfResult.fileName,
                    pdfUrl: pdfResult.pdfUrl,
                    error: pdfResult.error
                };

            } catch (error) {
                console.error(`处理运单 ${waybill.物流单号} 失败:`, error);

                // 尝试关闭对话框
                try {
                    await this.closePrintDialog();
                } catch (closeError) {
                    console.warn('关闭对话框失败:', closeError);
                }

                throw error;
            }
        }

        async clickPrintButton(waybill) {
            console.log(`🖨️ 点击打印按钮: ${waybill.物流单号}`);

            if (!waybill.打印按钮) {
                throw new Error('未找到打印按钮');
            }

            waybill.打印按钮.click();
            await this.delay(2000);

            return true;
        }

        async waitForPrintDialog(timeout = 10000) {
            const startTime = Date.now();
            while (Date.now() - startTime < timeout) {
                const dialog = document.querySelector('[data-testid="beast-core-drawer-content"]');
                if (dialog && dialog.textContent.includes('批量打印物流单据')) {
                    console.log('✅ 打印对话框已出现');
                    return true;
                }
                await this.delay(500);
            }
            throw new Error('打印对话框等待超时');
        }

        async uncheckPackingList() {
            console.log('📦 取消选择装箱单...');

            const checkboxes = document.querySelectorAll('[data-testid="beast-core-checkbox"]');
            for (const checkbox of checkboxes) {
                const text = checkbox.textContent || '';
                if (text.includes('装箱单')) {
                    const isChecked = checkbox.getAttribute('data-checked') === 'true';
                    if (isChecked) {
                        checkbox.click();
                        console.log('✅ 已取消选择装箱单');
                        await this.delay(1000);
                        return true;
                    }
                }
            }
            console.log('⚠️ 未找到装箱单复选框或已取消选择');
            return true;
        }

        async clickPrintConfirmButton() {
            const buttons = document.querySelectorAll('button');
            for (const button of buttons) {
                const text = button.textContent || '';
                if (text == '打印') {
                    button.click();
                    console.log('✅ 已点击打印按钮');
                    await this.delay(3000);
                    return true;
                }
            }

            throw new Error('未找到打印确认按钮');
        }

        // 修改 getPDFFromPrintPage 方法，修复PDF大小为0的问题
        async getPDFFromPrintPage(waybill) {
            console.log('📄 从打印页面获取PDF...');

            // 等待打印页面加载完成
            await this.delay(2000);

            // 获取PDF文件的URL
            const pdfSrcList = window.printBlocker.getDiscoveredUrls();
            let item = '';

            console.log('发现的URL列表:', pdfSrcList);

            for (let i = 0; i < pdfSrcList.length; i++) {
                if (pdfSrcList[i].includes('label') || pdfSrcList[i].includes('.pdf')) {
                    item = pdfSrcList[i];
                    console.log('找到PDF URL:', item);
                    break;
                }
            }

            const pdfSrc = item;
            console.log('最终PDF URL:', pdfSrc);

            window.printBlocker.setDiscoveredUrls();

            if (!pdfSrc) {
                throw new Error('未找到有效的PDF文件URL');
            }

            // 下载PDF文件 - 使用多种方法尝试
            let pdfBlob, pdfArrayBuffer;

            try {
                // 方法1: 使用fetch，添加更多请求头
                console.log('尝试使用fetch下载PDF...');
                const pdfResponse = await fetch(pdfSrc, {
                    method: 'GET', headers: {
                        'Accept': 'application/pdf, */*', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache'
                    }, credentials: 'include' // 包含cookies
                });

                if (!pdfResponse.ok) {
                    throw new Error(`下载PDF失败: ${pdfResponse.status} ${pdfResponse.statusText}`);
                }

                pdfBlob = await pdfResponse.blob();
                console.log('Fetch下载成功，文件大小:', pdfBlob.size);

            } catch (fetchError) {
                console.log('Fetch方法失败，尝试XHR方法:', fetchError.message);

                // 方法2: 使用XMLHttpRequest
                try {
                    pdfBlob = await this.fetchPDFWithXHR(pdfSrc);
                    console.log('XHR下载成功，文件大小:', pdfBlob.size);
                } catch (xhrError) {
                    console.log('XHR方法也失败:', xhrError.message);

                    // 方法3: 尝试使用iframe下载
                    try {
                        pdfBlob = await this.fetchPDFWithIframe(pdfSrc);
                        console.log('Iframe下载成功，文件大小:', pdfBlob.size);
                    } catch (iframeError) {
                        throw new Error(`所有下载方法都失败: ${iframeError.message}`);
                    }
                }
            }

            // 检查文件大小
            if (!pdfBlob || pdfBlob.size < 100) {
                console.error('PDF文件大小异常:', pdfBlob?.size);
                throw new Error('PDF文件大小异常，可能为空文件');
            }

            pdfArrayBuffer = await pdfBlob.arrayBuffer();

            // 验证PDF文件
            await this.validatePDF(pdfBlob, pdfArrayBuffer);

            // 根据命名设置生成文件名
            let fileName;
            if (this.settings.pdfNaming === 'order' && waybill.客户单号) {
                fileName = `${waybill.客户单号}.pdf`;
            } else if (this.settings.pdfNaming === 'waybill') {
                // 新增：使用服务商品牌命名
                fileName = `${waybill.物流单号}.pdf`;
            }

            console.log('✅ PDF文件获取成功，大小:', pdfBlob.size, 'bytes');
            console.log('📝 文件名:', fileName);

            return {
                success: true,
                pdfData: pdfArrayBuffer,
                pdfBlob: pdfBlob,
                pdfUrl: pdfSrc,
                pdfSize: pdfBlob.size,
                fileName: fileName
            };
        }

        // 使用XMLHttpRequest获取PDF（备用方法）
        async fetchPDFWithXHR(url) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.responseType = 'blob';

                // 设置请求头
                xhr.setRequestHeader('Accept', 'application/pdf, */*');
                xhr.setRequestHeader('Cache-Control', 'no-cache');
                xhr.setRequestHeader('Pragma', 'no-cache');

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        resolve(xhr.response);
                    } else {
                        reject(new Error(`XHR下载失败: ${xhr.status}`));
                    }
                };

                xhr.onerror = function () {
                    reject(new Error('XHR网络错误'));
                };

                xhr.ontimeout = function () {
                    reject(new Error('XHR请求超时'));
                };

                xhr.timeout = 15000;
                xhr.send();
            });
        }

        // 新增：使用iframe下载PDF（第三种方法）
        async fetchPDFWithIframe(url) {
            return new Promise((resolve, reject) => {
                const iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                iframe.src = url;

                iframe.onload = function () {
                    try {
                        // 尝试从iframe获取内容
                        setTimeout(() => {
                            try {
                                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                                // 这里可能需要根据实际iframe内容来提取PDF
                                console.log('Iframe加载完成，但需要手动处理内容');
                                reject(new Error('Iframe方法需要进一步实现'));
                            } catch (e) {
                                reject(new Error('无法访问iframe内容: ' + e.message));
                            }
                        }, 2000);
                    } catch (error) {
                        reject(error);
                    }
                };

                iframe.onerror = function () {
                    reject(new Error('Iframe加载失败'));
                };

                document.body.appendChild(iframe);

                // 10秒后清理
                setTimeout(() => {
                    if (iframe.parentNode) {
                        iframe.parentNode.removeChild(iframe);
                    }
                }, 10000);
            });
        }

        // 验证PDF文件
        async validatePDF(pdfBlob, pdfArrayBuffer) {
            // 检查文件大小
            if (pdfBlob.size < 100) {
                throw new Error('PDF文件大小异常，可能为空文件');
            }

            // 检查PDF文件头
            const header = new Uint8Array(pdfArrayBuffer, 0, 4);
            const headerStr = String.fromCharCode(...header);

            if (!headerStr.startsWith('%PDF')) {
                throw new Error('文件不是有效的PDF格式');
            }

            console.log('✅ PDF文件验证通过');
        }

        async closePrintDialog() {
            try {
                const closeButton = document.querySelector('[data-testid="beast-core-drawer-close"]');
                if (closeButton) {
                    closeButton.click();
                    await this.delay(1000);
                }
            } catch (error) {
                console.warn('关闭对话框失败:', error);
            }
        }

        // 新增：删除全部打印对话框
        removeAllPrintDialogs() {
            console.log('🗑️ 开始删除全部打印对话框...');

            // 方法1: 通过data-testid选择器
            const dialogs = document.querySelectorAll('[data-testid="beast-core-drawer"]');
            console.log(`找到 ${dialogs.length} 个打印对话框`);

            dialogs.forEach((dialog, index) => {
                try {
                    // 尝试多种删除方式
                    if (dialog.parentNode) {
                        dialog.parentNode.removeChild(dialog);
                        console.log(`✅ 删除对话框 ${index + 1} (方法1)`);
                    }
                } catch (error) {
                    console.warn(`删除对话框 ${index + 1} 失败:`, error);
                }
            });

            // 方法2: 通过类名选择器
            const drawerWrappers = document.querySelectorAll('.Drawer_outerWrapper_123');
            drawerWrappers.forEach((wrapper, index) => {
                try {
                    if (wrapper.parentNode) {
                        wrapper.parentNode.removeChild(wrapper);
                        console.log(`✅ 删除对话框 ${index + 1} (方法2)`);
                    }
                } catch (error) {
                    console.warn(`删除对话框 ${index + 1} 失败:`, error);
                }
            });

            // 方法3: 移除遮罩层
            const masks = document.querySelectorAll('.Drawer_mask_123');
            masks.forEach((mask, index) => {
                try {
                    if (mask.parentNode) {
                        mask.parentNode.removeChild(mask);
                        console.log(`✅ 删除遮罩层 ${index + 1}`);
                    }
                } catch (error) {
                    console.warn(`删除遮罩层 ${index + 1} 失败:`, error);
                }
            });

            // 方法4: 移除body上的可能样式
            // document.body.style.overflow = '';
            // document.body.style.position = '';
            // document.body.style.width = '';

            console.log('✅ 全部打印对话框删除完成');
            return dialogs.length + drawerWrappers.length;
        }

        // 新增：关闭所有打开的模态框和抽屉
        closeAllModals() {
            console.log('🔒 开始关闭所有模态框和抽屉...');

            // 查找所有可能的关闭按钮
            const closeButtons = document.querySelectorAll([
                '[data-testid="beast-core-drawer-close"]',
                '.Drawer_close_123',
                '.modal-close',
                '.close-button',
                '[aria-label="Close"]',
                '.ant-modal-close'
            ].join(','));

            closeButtons.forEach((btn, index) => {
                try {
                    btn.click();
                    console.log(`✅ 点击关闭按钮 ${index + 1}`);
                } catch (error) {
                    console.warn(`点击关闭按钮 ${index + 1} 失败:`, error);
                }
            });

            // 尝试ESC键关闭
            try {
                const escEvent = new KeyboardEvent('keydown', {
                    key: 'Escape',
                    code: 'Escape',
                    keyCode: 27,
                    which: 27,
                    bubbles: true
                });
                document.dispatchEvent(escEvent);
                console.log('✅ 发送ESC键事件');
            } catch (error) {
                console.warn('发送ESC键事件失败:', error);
            }

            // 移除可能存在的覆盖层
            const overlays = document.querySelectorAll([
                '.modal-backdrop',
                '.overlay',
                '.mask',
                '.Drawer_mask_123',
                '.ant-modal-mask'
            ].join(','));

            overlays.forEach((overlay, index) => {
                try {
                    if (overlay.parentNode) {
                        overlay.parentNode.removeChild(overlay);
                        console.log(`✅ 删除覆盖层 ${index + 1}`);
                    }
                } catch (error) {
                    console.warn(`删除覆盖层 ${index + 1} 失败:`, error);
                }
            });

            console.log('✅ 所有模态框关闭完成');
        }


        // 修改 generateExcelFile 方法，增加新字段
        async generateExcelFile() {
            console.log('📊 生成Excel文件...');

            try {
                await this.ensureXLSXLoaded();

                const wb = XLSX.utils.book_new();
                const successCount = this.results.filter(r => r.success).length;

                const excelData = this.results.map(item => {
                    const baseRow = {
                        '序号': item.序号,
                        '客户单号': item.客户单号,
                        '物流单号': item.物流单号,
                        'CW单号': item.CW单号 || '', // 新增字段
                        '服务商品牌': item.服务商品牌 || '', // 新增字段
                        '处理状态': item.success ? '成功' : '失败',
                        'PDF文件': item.success ? item.fileName : 'N/A',
                        '总块数': 'N/A',
                        '错误信息': item.error || '',
                        '处理时间': new Date().toLocaleString()
                    };

                    if (item.success && item.pdfData) {
                        const base64Data = this.arrayBufferToBase64(item.pdfData);
                        const chunks = this.splitBase64IntoChunks(base64Data, 32000);

                        baseRow['总块数'] = chunks.length;

                        chunks.forEach((chunk, index) => {
                            baseRow[`文件BASE${index + 1}`] = chunk;
                        });
                    }

                    return baseRow;
                });

                const ws = XLSX.utils.json_to_sheet(excelData);

                // 设置列宽，增加新字段的列宽
                const colWidths = [{wch: 8},   // 序号
                    {wch: 20},  // 客户单号
                    {wch: 20},  // 物流单号
                    {wch: 15},  // CW单号
                    {wch: 15},  // 服务商品牌
                    {wch: 10},  // 处理状态
                    {wch: 25},  // PDF文件
                    {wch: 10},  // 总块数
                    {wch: 30},  // 错误信息
                    {wch: 20}   // 处理时间
                ];

                for (let i = 1; i <= 10; i++) {
                    colWidths.push({wch: 50});
                }

                ws['!cols'] = colWidths;
                XLSX.utils.book_append_sheet(wb, ws, '物流面单处理结果');

                // 新增：添加服务商品牌统计表
                // this.addServiceBrandSummary(wb);
                // this.addBase64RecoveryInstructions(wb);

                const excelBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
                const timestamp = this.getTimestamp();
                const fileName = `物流面单处理结果_${timestamp}.xlsx`;

                this.downloadFile(excelBuffer, fileName, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

                // 更新完成消息，包含ZIP包信息
                const summary = `批量处理完成！
总运单数: ${this.results.length}
成功: ${successCount}
失败: ${this.results.length - successCount}

生成文件:
1. Excel文件: ${fileName} (包含详细处理日志和Base64数据)
2. PDF ZIP包: 物流面单PDF包_${timestamp}.zip (包含所有成功的PDF文件)

请查看下载文件夹获取文件。`;

                console.log(summary);
                this.sendExportComplete(fileName, successCount);

            } catch (error) {
                console.error('生成Excel文件失败:', error);
                this.sendExportError(error.message);
            }
        }

        // 新增：添加服务商品牌统计表
        addServiceBrandSummary(wb) {
            const brandStats = {};

            this.results.forEach(item => {
                const brand = item.服务商品牌 || '未知';
                if (!brandStats[brand]) {
                    brandStats[brand] = {
                        total: 0, success: 0, failed: 0
                    };
                }
                brandStats[brand].total++;
                if (item.success) {
                    brandStats[brand].success++;
                } else {
                    brandStats[brand].failed++;
                }
            });

            const summaryData = [['服务商品牌统计', '', '', ''], ['', '', '', ''], ['服务商品牌', '总运单数', '成功数', '失败数']];

            Object.keys(brandStats).forEach(brand => {
                const stats = brandStats[brand];
                summaryData.push([brand, stats.total, stats.success, stats.failed]);
            });

            // 添加总计行
            const totalStats = {
                total: this.results.length,
                success: this.results.filter(r => r.success).length,
                failed: this.results.filter(r => !r.success).length
            };

            summaryData.push(['总计', totalStats.total, totalStats.success, totalStats.failed]);

            const summaryWs = XLSX.utils.aoa_to_sheet(summaryData);

            // 设置列宽
            summaryWs['!cols'] = [{wch: 20},  // 服务商品牌
                {wch: 12},  // 总运单数
                {wch: 12},  // 成功数
                {wch: 12}   // 失败数
            ];

            XLSX.utils.book_append_sheet(wb, summaryWs, '服务商统计');
        }

        // 将Base64数据分割成多个块
        splitBase64IntoChunks(base64Data, chunkSize = 32000) {
            const chunks = [];
            for (let i = 0; i < base64Data.length; i += chunkSize) {
                chunks.push(base64Data.substring(i, i + chunkSize));
            }
            return chunks;
        }

        // ArrayBuffer 转 Base64 辅助方法
        arrayBufferToBase64(buffer) {
            if (!buffer) return '';

            const uint8Array = new Uint8Array(buffer);
            let binary = '';
            const len = uint8Array.length;

            for (let i = 0; i < len; i++) {
                binary += String.fromCharCode(uint8Array[i]);
            }

            return btoa(binary);
        }

        // 添加Base64数据恢复说明
        addBase64RecoveryInstructions(wb) {
            const instructions = [['Base64数据恢复说明', '', '', '', ''], ['', '', '', '', ''], ['数据存储结构:', '', '', '', ''], ['列名', '说明', '示例', '', ''], ['文件BASE1', 'Base64数据第1块', 'JVBERi0xLjQKMSAwIG9i...', '', ''], ['文件BASE2', 'Base64数据第2块', '...继续的数据...', '', ''], ['文件BASE3', 'Base64数据第3块', '...继续的数据...', '', ''], ['...', '...', '...', '', ''], ['文件BASEn', 'Base64数据第n块', '...结尾的数据...', '', ''], ['', '', '', '', ''], ['恢复步骤:', '', '', '', ''], ['1.', '查看"总块数"列，确认需要复制的块数', '', '', ''], ['2.', '按顺序复制文件BASE1 ~ 文件BASEn的所有数据', '', '', ''], ['3.', '将复制的数据按顺序拼接成一个完整的Base64字符串', '', '', ''], ['4.', '使用以下方法恢复PDF文件:', '', '', ''], ['', '', '', '', ''], ['JavaScript恢复代码:', '', '', '', ''], ['', '// 1. 拼接所有Base64块', '', '', ''], ['', 'const base64Data = base1 + base2 + base3 + ... + baseN;', '', '', ''], ['', '', '', '', ''], ['', '// 2. 转换为二进制数据', '', '', ''], ['', 'const binaryString = atob(base64Data);', '', '', ''], ['', 'const bytes = new Uint8Array(binaryString.length);', '', '', ''], ['', 'for (let i = 0; i < binaryString.length; i++) {', '', '', ''], ['', '  bytes[i] = binaryString.charCodeAt(i);', '', '', ''], ['', '}', '', '', ''], ['', '', '', '', ''], ['', '// 3. 创建Blob并下载', '', '', ''], ['', 'const blob = new Blob([bytes], { type: "application/pdf" });', '', '', ''], ['', 'const url = URL.createObjectURL(blob);', '', '', ''], ['', 'const a = document.createElement("a");', '', '', ''], ['', 'a.href = url;', '', '', ''], ['', 'a.download = "文件名.pdf";', '', '', ''], ['', 'a.click();', '', '', ''], ['', 'URL.revokeObjectURL(url);', '', '', ''], ['', '', '', '', ''], ['Python恢复代码:', '', '', '', ''], ['', 'import base64', '', '', ''], ['', '', '', '', ''], ['', '# 拼接所有Base64块', '', '', ''], ['', 'base64_data = base1 + base2 + base3 + ... + baseN', '', '', ''], ['', '', '', '', ''], ['', '# 解码并保存为PDF', '', '', ''], ['', 'pdf_data = base64.b64decode(base64_data)', '', '', ''], ['', 'with open("output.pdf", "wb") as f:', '', '', ''], ['', '    f.write(pdf_data)', '', '', ''], ['', '', '', '', ''], ['在线工具:', '', '', '', ''], ['', 'https://base64.guru/converter/decode/pdf', '', '', ''], ['', 'https://base64-to-pdf.com/', '', '', ''], ['', '', '', '', ''], ['注意事项:', '', '', '', ''], ['•', '必须按顺序复制所有块', '', '', ''], ['•', '不要遗漏任何块，否则无法恢复', '', '', ''], ['•', '确保复制的数据完整，没有多余的空格', '', '', ''], ['•', '如果恢复失败，请检查数据是否完整复制', '', '', '']];

            const instructionWs = XLSX.utils.aoa_to_sheet(instructions);

            // 设置列宽
            instructionWs['!cols'] = [{wch: 20},  // 第一列
                {wch: 35},  // 第二列
                {wch: 50},  // 第三列
                {wch: 10},  // 第四列
                {wch: 10}   // 第五列
            ];

            XLSX.utils.book_append_sheet(wb, instructionWs, '数据恢复说明');
        }

        // 从分块Base64数据恢复PDF文件的工具方法
        restorePdfFromChunkedBase64(base64Chunks, fileName = 'restored.pdf') {
            try {
                // 拼接所有Base64块
                const fullBase64Data = base64Chunks.join('');

                // Base64 转 ArrayBuffer
                const binaryString = atob(fullBase64Data);
                const bytes = new Uint8Array(binaryString.length);

                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }

                // 创建Blob并下载
                const blob = new Blob([bytes], {type: 'application/pdf'});
                const url = URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);

                // 清理URL
                setTimeout(() => URL.revokeObjectURL(url), 1000);

                console.log(`✅ PDF文件已恢复: ${fileName}`);
                return true;

            } catch (error) {
                console.error('恢复PDF文件失败:', error);
                return false;
            }
        }

        // 文件大小格式化辅助方法
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 新增：生成PDF ZIP包
        async generatePDFZipPackage() {
            console.log('📦 生成PDF ZIP包...');

            try {
                // 确保JSZip库已加载
                await this.ensureJSZipLoaded();

                const zip = new JSZip();
                const successResults = this.results.filter(r => r.success && r.pdfData);

                if (successResults.length === 0) {
                    console.log('⚠️ 没有成功的PDF文件可打包');
                    this.sendProgressUpdate(this.results.length, this.results.length, '没有成功的PDF文件可打包', '', 'info');
                    return;
                }

                // 直接将所有PDF文件添加到ZIP根目录
                successResults.forEach(result => {
                    if (result.pdfData && result.fileName) {
                        zip.file(result.fileName, result.pdfData);
                    }
                });

                // 添加处理结果说明文件
                const summary = this.generateZipSummary(successResults);
                zip.file('处理说明.txt', summary);

                // 生成ZIP文件
                const zipBlob = await zip.generateAsync({
                    type: 'blob',
                    compression: 'DEFLATE',
                    compressionOptions: {level: 6}
                });

                // 下载ZIP文件
                const timestamp = this.getTimestamp();
                const zipFileName = `物流面单PDF包_${timestamp}.zip`;

                this.downloadFile(zipBlob, zipFileName, 'application/zip');

                const summaryMsg = `✅ PDF ZIP包生成完成！
总文件数: ${successResults.length}
ZIP文件: ${zipFileName}
文件大小: ${this.formatFileSize(zipBlob.size)}
所有PDF文件已打包到根目录`;

                console.log(summaryMsg);
                this.sendProgressUpdate(this.results.length, this.results.length, summaryMsg, '', 'success');

            } catch (error) {
                console.error('生成PDF ZIP包失败:', error);
                this.sendProgressUpdate(this.results.length, this.results.length, `❌ PDF ZIP包生成失败: ${error.message}`, '', 'error');
            }
        }


        // 新增：生成ZIP包说明文件
        generateZipSummary(successResults) {
            const timestamp = new Date().toLocaleString();
            const totalSize = successResults.reduce((sum, result) => sum + (result.pdfData?.length || 0), 0);

            // 按服务商品牌统计
            const brandStats = {};
            successResults.forEach(result => {
                const brand = result.服务商品牌 || '其他';
                if (!brandStats[brand]) {
                    brandStats[brand] = [];
                }
                brandStats[brand].push(result);
            });

            let summary = `物流面单PDF包处理结果
生成时间: ${timestamp}
总运单数: ${this.results.length}
成功导出: ${successResults.length}
失败数量: ${this.results.length - successResults.length}
总文件大小: ${this.formatFileSize(totalSize)}

文件结构:
`;

            // 添加品牌文件夹结构
            Object.keys(brandStats).forEach(brand => {
                summary += `├── ${brand}/\n`;
                brandStats[brand].forEach((result, index) => {
                    const prefix = index === brandStats[brand].length - 1 ? '└── ' : '├── ';
                    summary += `${prefix}${result.fileName} - ${result.物流单号}${result.客户单号 ? ` (${result.客户单号})` : ''}\n`;
                });
                summary += '\n';
            });

            summary += `处理说明:
1. 所有PDF文件已按服务商品牌分类存储
2. 命名方式: ${this.settings.pdfNaming === 'order' ? '订单号' : this.settings.pdfNaming === 'service' ? '服务商品牌_运单号' : '运单号'}
3. 如有问题请参考Excel文件中的详细日志

-- 物流面单导出工具生成 --`;

            return summary;
        }

        // 新增：确保JSZip库加载
        async ensureJSZipLoaded() {
            if (typeof JSZip === 'undefined') {
                await this.loadJSZipLibrary();
            }
        }

        loadJSZipLibrary() {
            return new Promise((resolve, reject) => {
                if (typeof JSZip !== 'undefined') {
                    resolve();
                    return;
                }

                const script = document.createElement('script');
                script.src = chrome.runtime.getURL('jszip.min.js');
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }

        async ensureXLSXLoaded() {
            if (typeof XLSX === 'undefined') {
                await this.loadXLSXLibrary();
            }
        }

        loadXLSXLibrary() {
            return new Promise((resolve, reject) => {
                if (typeof XLSX !== 'undefined') {
                    resolve();
                    return;
                }

                const script = document.createElement('script');
                script.src = chrome.runtime.getURL('xlsx.full.min.js');
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }

        preloadLibraries() {
            // 预加载XLSX库
            this.loadXLSXLibrary().catch(console.warn);
            // 预加载JSZip库
            this.loadJSZipLibrary().catch(console.warn);
        }

        downloadFile(data, filename, mimeType) {
            const blob = new Blob([data], {type: mimeType});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        getTimestamp() {
            const now = new Date();
            return now.getFullYear() + String(now.getMonth() + 1).padStart(2, '0') + String(now.getDate()).padStart(2, '0') + '_' + String(now.getHours()).padStart(2, '0') + String(now.getMinutes()).padStart(2, '0') + String(now.getSeconds()).padStart(2, '0');
        }

        delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        stopExport() {
            this.isProcessing = false;
            console.log('⏹️ 导出任务已停止');

            chrome.runtime.sendMessage({
                action: 'exportStopped', data: {
                    processed: this.currentIndex + 1, total: this.results.length
                }
            });
        }

    }

    console.log('🚚 物流面单导出工具 - Content Script 开始加载');

    // 添加页面检测
    function isSupportedPage() {
        const url = window.location.href;
        const isTemuWaybillPage = url.includes('temu.com') && url.includes('/mmsos/waybill.html');

        if (!isTemuWaybillPage) {
            console.warn('⚠️ 当前页面不是Temu物流面单页面');
            return false;
        }

        console.log('✅ 检测到Temu物流面单页面');
        return true;
    }

    // 发送就绪消息给popup
    function sendReadyMessage() {
        setTimeout(() => {
            try {
                chrome.runtime.sendMessage({
                    action: 'contentScriptReady', data: {
                        url: window.location.href, timestamp: new Date().toISOString(), pageTitle: document.title
                    }
                }).then(() => {
                    console.log('✅ Content Script就绪消息发送成功');
                }).catch(error => {
                    console.log('⚠️ Content Script就绪消息发送失败（popup可能未打开）:', error.message);
                });
            } catch (error) {
                console.log('⚠️ 发送就绪消息异常:', error.message);
            }
        }, 1000);
    }

    // 页面加载完成后初始化
    function initialize() {
        console.log('🔄 Content Script初始化中...');

        if (!isSupportedPage()) {
            console.log('❌ 当前页面不支持，跳过初始化');
            return;
        }

        // 发送就绪消息
        sendReadyMessage();

        // 延迟初始化导出器，确保页面完全加载
        setTimeout(() => {
            try {
                if (!window.LogisticsExporter) {
                    window.LogisticsExporter = new LogisticsExporter();
                    console.log('✅ LogisticsExporter初始化完成');
                }
            } catch (error) {
                console.error('❌ LogisticsExporter初始化失败:', error);
            }
        }, 2000);
    }

    // 根据页面状态决定初始化时机
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        initialize();
    }
})();



